let orders = ajaxPostJSON('/order/user/select')
let $renderOrders = $('#render-orders')
// 渲染
function renderOrders(orders, status){
    $renderOrders.html('')
    let chose = $(`<select id="choseStatus" class="form-select"></select>`)
    ORDER_STATUS.forEach(function (status, i){
        chose.append(`<option value="${i}">${status}</option>`)
    })
    chose.prepend(`<option value="-1">全部订单</option>`)
    chose.val(status)
    $renderOrders.append(chose)
                 .append(`<p>&nbsp;&nbsp;共有` + orders.length + '条订单</p>')
    orders.forEach(function (order){
        $renderOrders.append(`
          <li class="shadow-sm">
        <table class="table" valign="middle">
            <tr>
                <th style="width: 300px">商品名称</th>
                <th style="width: 100px">供应商名称</th>
                <th style="width: 50px">数量</th>
                <th style="width: 80px">总价</th>
                <th style="width: 250px">创建时间</th>
                <th style="width: 100px">订单状态</th>
                <th>操作</th>
            </tr>
            <tr>
                <td><a href="/product.html?productId=${order['product']['id']}" class="text-decoration-none">${order['product']['name']}</a></td>
                <td>${order['provider']['name']}</td>
                <td>${order['number']}</td>
                <td class="text-danger">${order['price']}元</td>
                <td>${dateFormat('YYYY年mm月dd日 HH:MM:SS', new Date(order['createTime']))}</td>
                <td>${ORDER_STATUS[order['status']]}</td>
                <td>
                    
                    ${order['status'] === 0 ? `<button class="btn btn-primary" onclick="payOrder(${order['id']})">结算</button><button class="btn btn-danger" onclick="cancelOrder(${order['id']})">取消订单</button>` : ``}
                    ${order['status'] === 1 ? `<button class="btn btn-primary" onclick="showProduct('${order['provider']['contact']}',${order['provider']['tel']})">联系商家</button>` : ``}
                    ${order['status'] === 2 ? `<button class="btn btn-primary" onclick="showExpress()">查看物流</button>` : ``}
                    ${order['status'] === 3 ? `<button class="btn btn-primary" onclick="sureOrder(${order['id']})">确认收货</button>` : ``}
                    ${order['status'] === 4 ? `<button class="btn btn-success">交易完成</button>` : ``}
                </td>
            </tr>
        </table>
    </li>
        `)
    })

    // 当选择订单状态时, 查询相应状态的订单
    $('#choseStatus').on('change', function (){
        orders = ajaxPostJSON('/order/user/select?status=' + $(this).val())
        renderOrders(orders, $(this).val())
    })
}
////////////////////// 功能函数
// 结算订单
function payOrder(orderId){
    let result = ajaxCustom('POST', {url: '/order/update/pay/' + orderId})
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
// 取消订单
function cancelOrder(orderId){
    if(!confirm("确认要取消该订单吗？")) return
    let result = ajaxCustom('POST', {url: '/order/update/cancel/' + orderId})
    if(result['code'] === CODE_SUCCESS)
        ms_show_toast_reload(true, result['msg'])
    else
        ms_show_toast(false, result['msg'])
}
// 联系商家
function showProduct(contact, tel){
    ms_show_toast(true, '联系人: ' + contact + '\n联系方式: ' + tel)
}
// 确认收货
function sureOrder(orderId){
    let result = ajaxCustom('POST', {
        url: '/order/update/status/' + orderId,
        data : {'status': ORDER_STATUS_MAP['已收货']}
    })
    if(result['code'] === CODE_SUCCESS)
        ms_show_toast_reload(true, '操作成功!')
    else
        ms_show_toast(false, result['msg'])
}
// 查看物流
function showExpress(){
    ms_show_toast(true, '物流正在路上了，请耐心等待（功能待开发）')
}
$(document).ready(function (){
    // 默认是显示全部订单
    renderOrders(orders, -1)
})